package util.comunication.handler;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import util.comunication.Address;
import util.comunication.interfaces.IReceiveHandler;
/**
 * 
 * @author v
 *
 */
public class ReceiverHandlerMulticast implements IReceiveHandler {
	protected Address addr;
	protected MulticastSocket socket; 
	protected ExecutorService thread = null;
	protected int dimRP = 100;
	boolean threadLive = true;
	
	public ReceiverHandlerMulticast() {
		
	}

	@Override
	public void setAddres(Address addr) {
		this.addr = addr;
	}

	@Override
	public void create() throws UnknownHostException, IOException {
		InetAddress ia = InetAddress.getByName(addr.getIp());
		socket = new MulticastSocket (addr.getPort());
		socket.joinGroup(ia);
		thread = Executors.newSingleThreadExecutor();
		thread.execute(this);
	}

	@Override
	public void close() throws UnknownHostException, IOException {
		InetAddress ia = InetAddress.getByName(addr.getIp());
		socket.leaveGroup(ia);
		socket.close();
		threadLive = false; //Stoppo il thread
		thread.shutdown();
	}


	@Override
	public void run() {
		byte[] buffer = new byte[dimRP];
		DatagramPacket packet = new DatagramPacket(buffer, dimRP);
		while (threadLive) {
			try {
				socket.receive(packet);
				//ok ho ricevuto il packet adesso devo fare il delivery - inserisco in coda aspetto un tempo t
				String s = new String(packet.getData());
				System.out.println(s);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		packet = null;
	}
	
	
	

	@Override
	public void setDimRP(int dim) {
		this.dimRP = dim;
	}
	
	
	
	
	
	
}
